<style scoped lang="scss">
.bar {
  width: 100%;
  z-index: 99999;
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  i {
    margin: 8px;
    font-size: 20px;
  }
}
</style>
<template>
  <div class="bar">
    <!--        <el-tooltip class="item" effect="dark" content="清除" placement="bottom">-->
    <!--            <i class="el-icon-delete" @click="del(graph)"/>-->
    <!--        </el-tooltip>-->
    <!--        <el-tooltip class="item" effect="dark" content="剪切" placement="bottom">-->
    <!--            <i class="el-icon-document" @click="cut(graph)"/>-->
    <!--        </el-tooltip>-->
    <!--        <el-tooltip class="item" effect="dark" content="复制" placement="bottom">-->
    <!--            <i class="el-icon-document-copy" @click="copy(graph)"/>-->
    <!--        </el-tooltip>-->
    <!--        <el-tooltip class="item" effect="dark" content="粘贴" placement="bottom">-->
    <!--            <i class="el-icon-folder" @click="paste(graph)"/>-->
    <!--        </el-tooltip>-->
    <!--        <el-tooltip class="item" effect="dark" content="保存图片" placement="bottom">-->
    <!--            <i class="el-icon-picture-outline" @click="savePNG(graph)"/>-->
    <!--        </el-tooltip>-->
    <el-tooltip class="item" effect="dark" content="放大" placement="bottom">
      <i class="el-icon-zoom-in" @click="zoomFn(graph, 0.2)" />
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="缩小" placement="bottom">
      <i class="el-icon-zoom-out" @click="zoomFn(graph, -0.2)" />
    </el-tooltip>
    <el-tooltip
      class="item"
      effect="dark"
      content="适应屏幕"
      placement="bottom"
    >
      <i class="el-icon-full-screen" @click="centerFn(graph)" />
    </el-tooltip>
    <el-tooltip
      class="item"
      effect="dark"
      content="保存画布"
      placement="bottom"
    >
      <i class="el-icon-upload" @click="toJSON(graph)" />
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="执行" placement="bottom">
      <i class="el-icon-video-play" @click="exec(graph)" />
    </el-tooltip>
    <!--        <el-tooltip class="item" effect="dark" content="保存页面" placement="bottom">-->
    <!--            <i class="el-icon-upload" @click="saveFn(graph)"/>-->
    <!--        </el-tooltip>-->
    <!--        <el-tooltip class="item" effect="dark" content="加载保存页面" placement="bottom">-->
    <!--            <i class="el-icon-link" @click="loadFn()"/>-->
    <!--        </el-tooltip>-->
    <el-tooltip class="item" effect="dark" content="返回" placement="bottom">
      <i class="el-icon-right" @click="cancelEditGraph(graph)" />
    </el-tooltip>
  </div>
</template>

<script>
import { DataUri } from "@antv/x6";
import qs from "qs";

export default {
  name: "FlowTool",
  props: ["graph", "startFn"],
  data() {
    return {
      canvasParams: {},
    };
  },
  async mounted() {
    const params = {
      id: this.$route.query.id,
    };
    const res = await this.$store.dispatch(
      "feCanvasListById",
      qs.stringify(params, { indices: false })
    );
    this.canvasParams = res.data.data;
  },
  watch: {
    graph(newVal) {
      this.graph = newVal;
    },
  },
  methods: {
    copy(graph) {
      const cells = graph.getSelectedCells();
      if (cells.length) {
        graph.copy(cells);
      }
      return false;
    },
    cut(graph) {
      const cells = graph.getSelectedCells();
      if (cells.length) {
        graph.cut(cells);
      }
      return false;
    },
    paste(graph) {
      if (!graph.isClipboardEmpty()) {
        const cells = graph.paste({ offset: 32 });
        graph.cleanSelection();
        graph.select(cells);
      }
      return false;
    },
    del(graph) {
      graph.clearCells();
    },
    savePNG(graph) {
      graph.toPNG(
        (dataUri) => {
          // 下载
          DataUri.downloadDataUri(dataUri, "chart.png");
        },
        {
          backgroundColor: "white",
          padding: {
            top: 20,
            right: 30,
            bottom: 40,
            left: 50,
          },
          quality: 1,
        }
      );
    },
    saveSVG(graph) {
      graph.toSVG((dataUri) => {
        // 下载
        DataUri.downloadDataUri(DataUri.svgToDataUrl(dataUri), "chart.svg");
      });
    },
    print(graph) {
      graph.printPreview();
    },
    // request
    async toJSON(graph) {
      //   const res = await this.$store.dispatch("feCanvasSaveOrUpdate", {
      //     contentJson: JSON.stringify(graph.toJSON()),
      //     id: this.$route.query.id,
      //   });
      //   console.log(res);
      const { cells } = graph.toJSON();
      let lineParams = [],
        operatorsParams = [];
      for (let item of cells) {
        item.id = this.extractNumbers(item.id);
        if (item.source) {
          item.source.cell = this.extractNumbers(item.source.cell);
          item.source.port = this.extractNumbers(item.source.port);
        }
        if (item.target) {
          item.target.cell = this.extractNumbers(item.target.cell);
          item.target.port = this.extractNumbers(item.target.port);
        }
      }
      this.canvasParams.contentJson = JSON.stringify(cells);

      const lines = cells.filter((item) => item.shape === "dag-edge");
      const operators = cells.filter((item) => item.shape !== "dag-edge");
      for (let item of lines) {
        lineParams.push({
          id: item.id,
          canvasId: this.$route.query.id,
          pid: item.source.cell,
          cid: item.target.cell,
          lineParams: JSON.stringify(item),
        });
      }
      for (let [index, item] of operators.entries()) {
        operatorsParams.push({
          id: item.id,
          operatorname: item.shape + index,
          operatorType: item.shape,
          menuId: new Date().getTime() + index,
          canvasId: this.$route.query.id,
          pid: new Date().getSeconds() + index,
          coordinate: JSON.stringify(item),
        });
      }

      try {
        const res = await this.$store.dispatch(
          "feCanvasSaveOrUpdate",
          this.canvasParams
        );
        if (res.data.msg !== "执行成功") {
          // console.log(res.data)
          this.$message.error("保存失败");
          return;
        }
        this.$message.success("保存成功");
        // this.$store.commit('SET_CODE', '保存成功')
      } catch (e) {
        console.error(e);
      }
    },
    cancelEditGraph(graph) {
      // this.$confirm('是否需要保存图示？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      // })
      //     .then(() => {
      //         this.toJSON(graph)
      //         this.$router.push("/featureEngineering");
      //     })
      //     .catch(() => {
      //         this.$router.push("/featureEngineering");
      //     });
      this.toJSON(graph);
      this.$router.push("/featureEngineering");
    },

    zoomFn(graph, num) {
      graph.zoom(num);
      return false;
    },
    centerFn(graph) {
      const num = 1 - graph.zoom();
      num > 1 ? graph.zoom(num * -1) : graph.zoom(num);
      graph.centerContent();
      return false;
    },
    exec(graph) {},
    saveFn(graph) {
      localStorage.setItem(
        "x6Json",
        JSON.stringify(graph.toJSON({ diff: true }))
      );
    },
    loadFn() {
      this.timer && clearTimeout(this.timer);
      const x6Json = JSON.parse(localStorage.getItem("x6Json"));
      this.startFn(x6Json.cells);
    },

    // utils
    extractNumbers(str) {
      let numbers, extractedNumbers, result;
      if (str.match) {
        numbers = str.match(/\d+/g);
        extractedNumbers = numbers.map(Number);
        result = Number(extractedNumbers.join("").slice(0, 10));
        return result;
      }
      return str;
    },
  },
};
</script>


